package org.oneblog.init;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;

import org.oneblog.service.IArticleService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;

public class InitialContextListener extends ContextLoaderListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        super.contextInitialized(sce);

        ApplicationContext ac = (WebApplicationContext) sce.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

        System.out.println("spring web init " + ac);
        
        final IArticleService articleService = (IArticleService) ac.getBean("articleService");
        
        if(articleService != null) {
            ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
            executor.scheduleWithFixedDelay(new Runnable() {
                public void run() {
                    articleService.pushUrlToBaidu();
                }
            }, 0, 100, TimeUnit.MINUTES);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        
    }

}
